package org.example.managere.controller.feibiao;

import org.example.managere.dto.feibiao.AmAapDataDto;
import org.example.managere.entity.feibiao.AmAapData;
import org.example.managere.repository.feibiao.AmAapDataRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import jakarta.persistence.criteria.Predicate;
import jakarta.validation.Valid;
import java.util.*;

/**
 * 电机全维度运行监测数据表 Controller
 */
@RestController
@RequestMapping("/api/feibiao/knowledge/aap-data")
public class AmAapDataController {

    @Autowired
    private AmAapDataRepository aapDataRepository;

    /**
     * 分页查询
     */
    @GetMapping
    public Page<AmAapData> list(@RequestParam(defaultValue = "0") int page,
                                @RequestParam(defaultValue = "10") int size,
                                @RequestParam(defaultValue = "id,desc") String sort) {
        String[] sortArr = sort.split(",");
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortArr[1]), sortArr[0]));
        return aapDataRepository.findAll(pageable);
    }

    /**
     * 条件搜索（支持motorId、时间区间）
     */
    @GetMapping("/search")
    public Page<AmAapData> search(@RequestParam(required = false) String motorId,
                                  @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date startTime,
                                  @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") Date endTime,
                                  @RequestParam(defaultValue = "0") int page,
                                  @RequestParam(defaultValue = "10") int size,
                                  @RequestParam(defaultValue = "id,desc") String sort) {
        String[] sortArr = sort.split(",");
        Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.fromString(sortArr[1]), sortArr[0]));
        Specification<AmAapData> spec = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (motorId != null && !motorId.isEmpty()) {
                predicates.add(cb.equal(root.get("motorId"), motorId));
            }
            if (startTime != null) {
                predicates.add(cb.greaterThanOrEqualTo(root.get("timestamp"), startTime));
            }
            if (endTime != null) {
                predicates.add(cb.lessThanOrEqualTo(root.get("timestamp"), endTime));
            }
            return cb.and(predicates.toArray(new Predicate[0]));
        };
        return aapDataRepository.findAll(spec, pageable);
    }

    /**
     * 新增
     */
    @PostMapping
    public AmAapData create(@Valid @RequestBody AmAapDataDto dto) {
        AmAapData entity = new AmAapData();
        BeanUtils.copyProperties(dto, entity);
        return aapDataRepository.save(entity);
    }

    /**
     * 更新
     */
    @PutMapping("/{id}")
    public AmAapData update(@PathVariable Integer id, @Valid @RequestBody AmAapDataDto dto) {
        Optional<AmAapData> optional = aapDataRepository.findById(id);
        if (!optional.isPresent()) {
            throw new RuntimeException("记录不存在");
        }
        AmAapData entity = optional.get();
        BeanUtils.copyProperties(dto, entity, "id");
        return aapDataRepository.save(entity);
    }

    /**
     * 详情
     */
    @GetMapping("/{id}")
    public AmAapData detail(@PathVariable Integer id) {
        return aapDataRepository.findById(id).orElseThrow(() -> new RuntimeException("记录不存在"));
    }

    /**
     * 删除
     */
    @DeleteMapping("/{id}")
    public void delete(@PathVariable Integer id) {
        aapDataRepository.deleteById(id);
    }
} 